#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import fcntl
import numpy
import posix_ipc

__proxy_list = []

def add_proxy(proxy):
    __proxy_list.append(proxy)

def remove_proxy(proxy):
    __proxy_list.remove(proxy)
    '''
    for i in __proxy_list:
        if i is proxy:
            __proxy_list.remove(proxy)
    '''

def relase_proxy():
    for i in __proxy_list:
        i.release()
    __proxy_list.clear()

class VideoMMapProxy():
    def __init__(self):
        self.sempty = None
        self.sfull = None
    def init(self, prefix):
        prefix = "/" + prefix.replace("/", ".")
        empty = prefix + ".empty"
        full = prefix + ".full"
        self.sempty = posix_ipc.Semaphore(empty, posix_ipc.O_CREAT, initial_value=1)
        self.sfull = posix_ipc.Semaphore(full, posix_ipc.O_CREAT, initial_value=0)
        print("create Semaphore sempty:", empty)
        print("create Semaphore full:", full)
        add_proxy(self)
    def release(self):
        if self.sempty:
            self.sempty.close()
            self.sempty = None
        if self.sfull:
            self.sfull.close()
            self.sfull = None
        remove_proxy(self)
    def read(self, mm, f, shape):
        try:
            self.sfull.acquire(0.2)
        except Exception as e:
            return None
        fcntl.flock(f, fcntl.LOCK_EX)
        img = numpy.ndarray(shape=shape, dtype=numpy.uint8, buffer=mm).copy()
        fcntl.flock(f, fcntl.LOCK_UN)
        self.sempty.release()
        return img
    @staticmethod
    def send(mm, img):
        mm.seek(0)
        buffer = img.tobytes()
        mm.write(buffer)
    @staticmethod
    def release_proxy():
        relase_proxy()